/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

import com.yihu.wlyy.entity.consult.ConsultPublic;

public interface ConsultPublicDao extends PagingAndSortingRepository<ConsultPublic, Long>, JpaSpecificationExecutor<ConsultPublic> {

	ConsultPublic findByConsult(String consult);

	// 回复数量+1
	@Modifying
	@Query("update ConsultPublic a set a.amount = a.amount + 1 where a.consult = ?1")
	int increaseAmount(String consult);

	// 患者未读数量+1
	@Modifying
	@Query("update ConsultPublic a set a.unread = a.unread + 1 where a.consult = ?1")
	int increaseUnread(String consult);

	// 清空未读数量
	@Modifying
	@Query("update ConsultPublic a set a.unread = 0 where a.consult = ?1")
	int clearUnread(String consult);

	// 查询医生回答过的公共咨询记录
	@Query("SELECT a FROM ConsultPublic a, ConsultPublicReply b WHERE a.del = '1' and a.consult = b.consult and b.doctor = ?1 GROUP BY a.consult ORDER BY a.czrq DESC")
	Page<ConsultPublic> findRepliedPublicQuestionByDoctor(String doctor, Pageable pageRequest);

	@Query("SELECT a FROM ConsultPublic a, ConsultPublicReply b WHERE a.del = '1' and a.consult = b.consult and b.doctor = ?1 and a.id < ?2 GROUP BY a.consult ORDER BY a.czrq DESC")
	Page<ConsultPublic> findRepliedPublicQuestionByDoctor(String doctor, long id, Pageable pageRequest);
	
	@Query("SELECT a FROM ConsultPublic a, ConsultPublicReply b WHERE a.del = '1' and a.consult = b.consult and b.doctor = ?1 and a.disease = ?2 GROUP BY a.consult ORDER BY a.czrq DESC")
	Page<ConsultPublic> findRepliedPublicQuestionByDoctor(String doctor, String disease, Pageable pageRequest);

	@Query("SELECT a FROM ConsultPublic a, ConsultPublicReply b WHERE a.del = '1' and a.consult = b.consult and b.doctor = ?1 and a.disease = ?2 and a.id < ?3 GROUP BY a.consult ORDER BY a.czrq DESC")
	Page<ConsultPublic> findRepliedPublicQuestionByDoctor(String doctor, String disease, long id, Pageable pageRequest);

}
